import { useState, useEffect } from "react";
import styles from "./ProductManage.module.css";

interface ProductItem {
  id: number;
  team: string;
  img: string;
  typeOf: string;
  productName: string;
  sku: string;
//   规格?: string;
//   入库价格?: number;
//   出库价格?: number;
}

interface ApiResponse {
  totalCount: number;
  totalPage: number;
  items: ProductItem[];
  code: number;
  msg: string | null;
  data: any;
}

interface SearchParams {
  pageIndex: number;
  pageSize: number;
  SKU?: string;
  ProductName?: string;
  TypeOf?: string;
  Team?: string;
}

const ProductManage = () => {
  const [data, setData] = useState<ProductItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState<SearchParams>({
    pageIndex: 1,
    pageSize: 10
  });
  const [total, setTotal] = useState(0);
  const [selectedItems, setSelectedItems] = useState<number[]>([]);
  const [allSelected, setAllSelected] = useState(false);

  // 搜索表单状态
  const [searchForm, setSearchForm] = useState({
    SKU: '',
    ProductName: '',
    TypeOf: '',
    Team: ''
  });

  // 获取产品数据
  const fetchProducts = async () => {
    try {
      setLoading(true);
      const queryParams = new URLSearchParams();
      
      // 添加分页参数
      queryParams.append('PageIndex', searchParams.pageIndex.toString());
      queryParams.append('PageSize', searchParams.pageSize.toString());
      
      // 添加搜索参数
      if (searchParams.SKU) queryParams.append('SKU', searchParams.SKU);
      if (searchParams.ProductName) queryParams.append('ProductName', searchParams.ProductName);
      if (searchParams.TypeOf) queryParams.append('TypeOf', searchParams.TypeOf);
      if (searchParams.Team) queryParams.append('Team', searchParams.Team);

      const response = await fetch(`http://localhost:38925/api/ProductManage/GetProductManage?${queryParams}`);
      const result: ApiResponse = await response.json();
      
      console.log('API响应数据:', result); // 添加调试日志
      
      if (result.code === 0) {
        setData(result.items || []);
        setTotal(result.totalCount || 0);
      } else {
        console.error('获取数据失败:', result.msg);
        setData([]);
        setTotal(0);
      }
    } catch (error) {
      console.error('网络请求失败:', error);
      setData([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProducts();
  }, [searchParams]);

  // 处理搜索
  const handleSearch = () => {
    setSearchParams({
      ...searchParams,
      pageIndex: 1,
      ...searchForm
    });
  };

  // 处理重置
  const handleReset = () => {
    setSearchForm({
      SKU: '',
      ProductName: '',
      TypeOf: '',
      Team: ''
    });
    setSearchParams({
      pageIndex: 1,
      pageSize: 10
    });
  };

  // 处理分页
  const handlePageChange = (page: number) => {
    setSearchParams({
      ...searchParams,
      pageIndex: page
    });
  };

  // 处理全选
  const handleSelectAll = () => {
    if (allSelected) {
      setSelectedItems([]);
    } else {
      setSelectedItems(data.map(item => item.id));
    }
    setAllSelected(!allSelected);
  };

  // 处理单选
  const handleSelectItem = (id: number) => {
    if (selectedItems.includes(id)) {
      setSelectedItems(selectedItems.filter(item => item !== id));
    } else {
      setSelectedItems([...selectedItems, id]);
    }
  };

  // 计算总页数
  const totalPages = Math.ceil(total / searchParams.pageSize);

  return (
    <div className={styles.container}>
      {/* 搜索表单 */}
      <div className={styles.searchForm}>
        <div className={styles.searchRow}>
          <input
            type="text"
            placeholder="SKU"
            className={styles.searchInput}
            value={searchForm.SKU}
            onChange={(e) => setSearchForm({...searchForm, SKU: e.target.value})}
          />
          <input
            type="text"
            placeholder="产品名称"
            className={styles.searchInput}
            value={searchForm.ProductName}
            onChange={(e) => setSearchForm({...searchForm, ProductName: e.target.value})}
          />
          <select
            className={styles.searchInput}
            value={searchForm.TypeOf}
            onChange={(e) => setSearchForm({...searchForm, TypeOf: e.target.value})}
          >
            <option value="">类别</option>
            <option value="电子产品">电子产品</option>
            <option value="测试1">测试1</option>
          </select>
          <select
            className={styles.searchInput}
            value={searchForm.Team}
            onChange={(e) => setSearchForm({...searchForm, Team: e.target.value})}
          >
            <option value="">团队</option>
            <option value="深圳畅运达">深圳畅运达</option>
            <option value="RAKUSHIN">RAKUSHIN</option>
          </select>
          <button className={styles.searchButton} onClick={handleSearch}>
            搜索
          </button>
          <button className={styles.resetButton} onClick={handleReset}>
            重置
          </button>
        </div>
      </div>

      {/* 操作按钮 */}
      <div className={styles.actionButtons}>
        <button className={styles.addButton}>新增产品</button>
        <button className={styles.importButton}>导入Excel</button>
        <button className={styles.exportButton}>导入模板</button>
      </div>

      {/* 数据表格 */}
      <div className={styles.tableContainer}>
        <table className={styles.table}>
          <thead className={styles.tableHeader}>
            <tr>
              <th>
                <input
                  type="checkbox"
                  className={styles.checkbox}
                  checked={allSelected}
                  onChange={handleSelectAll}
                />
              </th>
              <th>序号</th>
              <th>团队</th>
              <th>图片</th>
              <th>类别</th>
              <th>产品名称</th>
              <th>SKU</th>
              {/* <th>规格</th>
              <th>入库价格(￥)</th>
              <th>出库价格(￥)</th> */}
              <th>操作</th>
            </tr>
          </thead>
          <tbody className={styles.tableBody}>
            {loading ? (
              <tr>
                <td colSpan={11} className={styles.loading}>
                  加载中...
                </td>
              </tr>
            ) : data.length === 0 ? (
              <tr>
                <td colSpan={11} className={styles.noData}>
                  暂无数据
                </td>
              </tr>
            ) : (
              data.map((item, index) => (
                <tr key={item.id} style={{ backgroundColor: index === 6 ? '#fff2e8' : 'transparent' }}>
                  <td>
                    <input
                      type="checkbox"
                      className={styles.checkbox}
                      checked={selectedItems.includes(item.id)}
                      onChange={() => handleSelectItem(item.id)}
                    />
                  </td>
                  <td>{(searchParams.pageIndex - 1) * searchParams.pageSize + index + 1}</td>
                  <td>
                    <a href="#" className={styles.productName}>
                      {item.team}
                    </a>
                  </td>
                  <td>
                    {item.img ? (
                      <img src={item.img} alt="产品图片" className={styles.productImage} />
                    ) : (
                      <div className={styles.productImage} style={{ backgroundColor: '#f0f0f0', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '12px' }}>
                        无图
                      </div>
                    )}
                  </td>
                  <td>{item.typeOf}</td>
                  <td>{item.productName}</td>
                  <td>{item.sku}</td>
                  {/* <td>{item.规格 || '-'}</td>
                  <td>{item.入库价格 || '-'}</td>
                  <td>{item.出库价格 || '-'}</td> */}
                  <td>
                    <button className={`${styles.actionButton} ${styles.viewButton}`}>
                      查看明细
                    </button>
                    <button className={`${styles.actionButton} ${styles.editButton}`}>
                      编辑
                    </button>
                    <button className={`${styles.actionButton} ${styles.modifyButton}`}>
                      修改
                    </button>
                    <button className={`${styles.actionButton} ${styles.deleteButton}`}>
                      删除
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>

        {/* 分页 */}
        <div className={styles.pagination}>
          <div className={styles.paginationInfo}>
            共 {total} 条记录，第 {searchParams.pageIndex} 页，共 {totalPages} 页
          </div>
          <div className={styles.paginationControls}>
            <button
              className={styles.paginationButton}
              disabled={searchParams.pageIndex === 1}
              onClick={() => handlePageChange(1)}
            >
              首页
            </button>
            <button
              className={styles.paginationButton}
              disabled={searchParams.pageIndex === 1}
              onClick={() => handlePageChange(searchParams.pageIndex - 1)}
            >
              上一页
            </button>
            <input
              type="number"
              className={styles.paginationInput}
              value={searchParams.pageIndex}
              onChange={(e) => {
                const page = parseInt(e.target.value);
                if (page >= 1 && page <= totalPages) {
                  handlePageChange(page);
                }
              }}
            />
            <button
              className={styles.paginationButton}
              disabled={searchParams.pageIndex === totalPages}
              onClick={() => handlePageChange(searchParams.pageIndex + 1)}
            >
              下一页
            </button>
            <button
              className={styles.paginationButton}
              disabled={searchParams.pageIndex === totalPages}
              onClick={() => handlePageChange(totalPages)}
            >
              末页
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ProductManage; 